package com.hongpeiming.picupload.controller;

import com.alibaba.fastjson.JSON;
import com.hongpeiming.picupload.pojo.JsonResult;
import com.hongpeiming.picupload.pojo.Pic;
import com.hongpeiming.picupload.pojo.User;
import com.hongpeiming.picupload.service.PicService;
import com.hongpeiming.picupload.service.UserService;
import com.hongpeiming.picupload.utils.ImageUtil;
import com.hongpeiming.picupload.utils.Md5CaculateUtil;
import com.hongpeiming.picupload.utils.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
public class UploadController {
    @Autowired
    UserService userService;

    @Autowired
    PicService picService;


    @Value("${uploadPicPath}")
    private String uploadPicPath;

    @Value("${filePath}")
    private String filePath;

    @Value("${urlPath}")
    private String urlPath;

    @Value("${RandomStringNumber}")
    private Integer RandomStringNumber;

    private JsonResult res;






    //上传页面
    @RequestMapping("/UploadPic")
    public String UploadPic(Model model, HttpSession session)
    {
        System.out.print("检测登录状态：");
        if (session.getAttribute("User")!=null)
        {
            System.out.println("存在登录用户");
            User user = (User) session.getAttribute("User");
            System.out.println(user.getUserAccount());
            model.addAttribute("username",user.getUserAccount());
        }else
        {
            System.out.println("未登录");
        }
        return "UploadPic";
    }


    //管理自己上传的所有图片
    @RequestMapping("/ManagerPic")
    public String ManagerPic(Model model, HttpSession session)
    {
        List<Pic> picList = new ArrayList<>();
        System.out.print("检测登录状态：");
        if (session.getAttribute("User")!=null)
        {
            System.out.println("存在登录用户");
            User user = (User) session.getAttribute("User");
            System.out.println(user.getUserAccount());
            model.addAttribute("username",user.getUserAccount());
            try {
                picList = picService.showMyPic(user.getUserId());
            }catch (Exception e)
            {
                System.out.println(e);
            }

        }else
        {
            System.out.println("未登录");
        }
        model.addAttribute("picList",picList);
        String jsonPicList = JSON.toJSONString(picList);
        model.addAttribute("jsonPicList",jsonPicList);
        return "ManagerPic";
    }


    //图片上传接口
    @RequestMapping("/upload/UplaodPic")
    @ResponseBody
    public String SingleUplaod(HttpSession session, HttpServletRequest request) throws IOException
    {
        Integer userId = 0;
        try {
            User user = (User) session.getAttribute("User");
            userId = user.getUserId();
        }catch (Exception e)
        {
            res = new JsonResult();
            res.setCode(0);
            res.setMsg("登录信息失效，请重新登录");
            res.setData("");
            return JSON.toJSONString(res);
        }

        //返回Json信息
        res = new JsonResult();
        List<Pic> pics = new ArrayList<>();

        //开始上传时间
        long startTime = System.currentTimeMillis();

        //上传地址
        String appPath = uploadPicPath;//session.getServletContext().getRealPath(filePath);

        //根据年月日存放图片
        Calendar data = Calendar.getInstance();
        String TimePath = "\\"+data.get(Calendar.YEAR)+"\\"+data.get(Calendar.MONTH)+"\\"+data.get(Calendar.DATE);
        appPath = appPath + TimePath;

        File appRootDir = new File(appPath);
        if (!appRootDir.exists()) {
            System.out.println("存储app的文件夹不存在 appPath= " + appPath);
            //创建这个路径的文件夹
            appRootDir.mkdirs();
        } else {
            System.out.println("存储app的文件夹存在 appPath= " + appPath);
        }


        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        //判断 request 是否有文件上传
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            //获取多个上传文件name
            Iterator<String> names = multiRequest.getFileNames();


            while (names.hasNext()) {
                MultipartFile file = multiRequest.getFile(names.next().toString());


                if (file != null) {
                    String OriginalFilename = file.getOriginalFilename();

                    String FilenameArray[] = OriginalFilename.split("\\.");
                    String prefix = FilenameArray[0];
                    String suffix = FilenameArray[1];

                    String RandomPrefix;



                    //File初始化参数(存放位置，文件名称)
                    File appFile;
                    for (;;)
                    {
                        RandomPrefix = RandomString.getRandomString(RandomStringNumber);
                        //String FinalName = RandomPrefix+"."+suffix;
                        //File FinalFile = new File(FinalName);
                        appFile = new File(appRootDir, RandomPrefix);
                        if (!appFile.exists())
                        {
                            System.out.println("当前随机文件名未重复，可用！");
                            break;
                        }

                    }


                    //保存到指定位置 指定名称
                    file.transferTo(appFile);
                    String FileMD5 = Md5CaculateUtil.getMD5(appFile);
                    System.out.println("FileMD5:"+FileMD5);

                    Pic pic = new Pic();
                    pic.setPicUploaderId(userId);
                    pic.setPicName(prefix.replace("-","_"));
                    pic.setPicUploadData(new Date());
                    pic.setPicMd5(FileMD5);
                    pic.setPicSize((int) appFile.length()/1024+1);
                    pic.setPicType(suffix);
                    pic.setPicStatus(0);

                    //查询是否有重复
                    if(picService.isRepeatMD5(FileMD5))
                    {
                        //如果有 使用之前的文件 并删除重复文件
                        System.out.println("FileMD5:"+FileMD5+"有重复！");
                        String FilePath = picService.findTheSameMD5FilePath(FileMD5);
                        if (FilePath!=null)
                        {
                            pic.setPicUrlPath(FilePath);
                            appFile.delete();
                        }
                        else
                        {
                            pic.setPicUrlPath(urlPath+TimePath+"\\"+RandomPrefix);
                        }
                    }else
                    {
                        pic.setPicUrlPath(urlPath+TimePath+"\\"+RandomPrefix);
                    }

                    //保存
                    Integer picId = picService.uploadSinglePic(pic);
                    System.out.println("保存信息到Json数据中");
                    pics.add(pic);

                }
            }
        }

        //结束时间
        long endTime = System.currentTimeMillis();

        res.setCode(1);
        res.setMsg("上传完毕<br>上传时间：" + String.valueOf(endTime - startTime) + "ms");
        res.setData(pics);
        return JSON.toJSONString(res);
    }


    //获取图片接口  所有获取图片请求都由此接口处理
    @RequestMapping("/loadpic/{PicId}")
    @ResponseBody
    public void getImg(Map<String, Object> model, @PathVariable("PicId")Integer PicId,HttpServletResponse response, HttpServletRequest request) throws IOException {

        //设置header
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);

        OutputStream os = response.getOutputStream();
        byte[] btImg = null;
        // FIXME: test datas, new data will replace
        Pic pic = picService.findPicByKey(PicId);



        System.out.println("PicId:"+PicId);
        if(pic.getPicStatus().equals(0)) {
            System.out.println("该图片为公开图片");
            btImg = ImageUtil.getBytes(filePath+pic.getPicUrlPath());
        } else if(pic.getPicStatus().equals(10)){
            System.out.println("未找到该图片");
            btImg = ImageUtil.getBytes(uploadPicPath+"\\noacess");
        } else {
            System.out.println("待定义显示图片");
            btImg = ImageUtil.getBytes(uploadPicPath+"\\noacess");
        }

        os.write(btImg);
        os.flush();
    }

    //保留图片原格式的获取图片接口
    @RequestMapping("/loadpicfile/{PicId}-{prefix}.{suffix}")
    @ResponseBody
    public void getImgfile(Map<String, Object> model, @PathVariable("prefix")String prefix, @PathVariable("suffix")String suffix, @PathVariable("PicId")Integer PicId,HttpServletResponse response, HttpServletRequest request,HttpSession session) throws IOException {

        //设置header
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);

        OutputStream os = response.getOutputStream();
        byte[] btImg = null;
        // FIXME: test datas, new data will replace
        Pic pic = picService.findPicByKey(PicId);
        int userId = 0;
        try {
            userId = (int) session.getAttribute("userId");
        }catch (Exception e){

        }



        //判断图片ID与图片名称是否符合
        //找不到该图片 || 文件名称不吻合
        if(pic.getPicStatus().equals(10)||(!pic.getPicName().equals(prefix))||(!pic.getPicType().equals(suffix))){

            System.out.println("未找到该图片");
            btImg = ImageUtil.getBytes(uploadPicPath+"\\unfound");
        } else if(pic.getPicStatus().equals(0))
        {   //公开图片
            System.out.println("该图片为公开图片");
            btImg = ImageUtil.getBytes(filePath+pic.getPicUrlPath());
        } else if(pic.getPicUploaderId()==userId)
        {
            //非公开图片 但登录账号为本人
            System.out.println("上传者浏览");
            btImg = ImageUtil.getBytes(filePath+pic.getPicUrlPath());
        }else {
            System.out.println("待定义显示图片");
            btImg = ImageUtil.getBytes(uploadPicPath+"\\noacess");
        }

        os.write(btImg);
        os.flush();
    }


    //删除图片接口
    @RequestMapping("/deletepic/{PicId}")
    @ResponseBody
    public String deletePic(@PathVariable("PicId")Integer PicId)
    {
        try {
            Pic pic = picService.findPicByKey(PicId);

            //删除数据库中存储信息
            picService.deletePic(PicId);
            //检查是否为同一文件下最后一条存储数据
            if (picService.isNeedDelete(pic.getPicMd5()))
            {
                String PicUrl = filePath + pic.getPicUrlPath();
                File file = new File(PicUrl);
                file.delete();
                return "删除成功！";
            }
        }catch (Exception e)
        {
            System.out.println(e);

        }
        return "删除失败！";
    }

    //修改备注接口
    @RequestMapping("/editremark/{PicId}")
    @ResponseBody
    public String editremark(@PathVariable("PicId")Integer PicId,String remark)
    {
        try {
            picService.editremark(PicId,remark);
            return "修改成功！";
        }catch (Exception e)
        {
            System.out.println(e);
        }
        return "修改失败！";
    }

    //修改图片查看权限
    @RequestMapping("/changepicstatus/{PicId}/{value}")
    @ResponseBody
    public String changepicstatus(@PathVariable("PicId")Integer PicId,@PathVariable("value")Integer value)
    {
        try {
            picService.changestatus(PicId,value);
            return "修改成功！";
        }catch (Exception e)
        {
            System.out.println(e);
        }
        return "修改失败！";
    }
}
